<template>
  <div class="layout">
    <div class="main-box">
      <div class="tit">规格管理</div>
      <div class="selector-box">
        <el-form :model="searchInfo" label-position="top">
          <div class="flex-container">
            <el-form-item label="规格名称">
              <div class="input-wrapper">
                <el-input
                  v-model="searchInfo.specKey"
                  placeholder="请输入规格名称"
                  clearable
                  @input="handleSearch"
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><search /></el-icon>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item label="中文名称">
              <div class="input-wrapper">
                <el-input
                  v-model="searchInfo.displayName"
                  placeholder="请输入规格中文名称"
                  clearable
                  @input="handleSearch"
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><search /></el-icon>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item label="规格符号">
              <div class="input-wrapper">
                <el-input
                  v-model="searchInfo.prefix"
                  placeholder="请输入规格符号"
                  clearable
                  @input="handleSearch"
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><search /></el-icon>
                  </template>
                </el-input>
                <el-button
                  type="primary"
                  icon="search"
                  @click="handleSearch"
                  style="height: 100%"
                  >查询</el-button
                >
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="btn-list">
        <div class="left-btns">
          <el-button icon="plus" type="primary" @click="handleAddSpec">
            新建规格
          </el-button>
          <el-button icon="refresh" text @click="handleReset"> 刷新 </el-button>
        </div>
      </div>
      <div class="table-box">
        <el-table
          ref="singleTableRef"
          :data="tableData"
          style="width: 100%; height: 100%"
          class="custom-table"
          border
        >
          <el-table-column
            type="index"
            width="60"
            label="编号"
            align="center"
          />
          <el-table-column
            prop="specKey"
            label="规格名称"
            style="width: 20%"
            align="center"
          />
          <el-table-column
            prop="displayName"
            label="中文名称"
            style="width: 20%"
            align="center"
          />
          <el-table-column
            prop="prefix"
            label="规格符号"
            style="width: 20%"
            align="center"
          />
          <el-table-column
            prop="dataType"
            label="数据类型"
            style="width: 20%"
            align="center"
          />
          <el-table-column
            prop="operation"
            label="操作"
            width="80"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="Edit"
                plain
                size="small"
                @click="handleEdit(row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--新建规格-->
    <el-dialog
      v-model="dialogVisible"
      title="新建规格"
      width="40%"
      @closed="handleDialogClose"
      draggable
    >
      <el-form
        ref="specFormRef"
        :model="specForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="规格名称" prop="specKey">
          <el-input
            v-model="specForm.specKey"
            placeholder="请输入英文规格名称"
          />
        </el-form-item>
        <el-form-item label="中文名称" prop="displayName">
          <el-input
            v-model="specForm.displayName"
            placeholder="请输入中文名称"
          />
        </el-form-item>
        <el-form-item label="规格符号" prop="prefix">
          <el-input v-model="specForm.prefix" placeholder="请输入规格符号" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-input v-model="specForm.dataType" placeholder="请输入数据类型" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!--编辑规格-->
    <el-dialog
      v-model="dialogEditVisible"
      title="编辑规格"
      width="40%"
      @closed="handleDialogClose"
      draggable
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="规格名称" prop="specKey">
          <el-input v-model="editForm.specKey" placeholder="规格名称" />
        </el-form-item>
        <el-form-item label="中文名称" prop="displayName">
          <el-input
            v-model="editForm.displayName"
            placeholder="请输入中文名称"
          />
        </el-form-item>
        <el-form-item label="规格符号" prop="prefix">
          <el-input v-model="editForm.prefix" placeholder="请输入规格符号" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-input v-model="editForm.dataType" placeholder="请输入数据类型" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, type FormInstance } from "element-plus";
import axios from "axios";
import request from "@/utils/request";

interface SpecItem {
  id: number;
  specKey: string; // 规格唯一标识
  prefix: string; // 缩写符号（如L）
  dataType: string; // 数据类型
  displayName: string; // 中文名
}

export default defineComponent({
  components: { Search },
  setup() {
    const formRef = ref<FormInstance>();
    const searchInfo = reactive({
      specKey: "",
      prefix: "",
      dataType: "",
      displayName: "",
    });

    const originTableData = ref<SpecItem[]>([]); //存储原始数据
    const tableData = ref<SpecItem[]>([]);

    // 获取数据方法
    const getList = async () => {
      try {
        const response = await request({
          method: "get",
          url: "inventory/specification/getAllSpecifications",
          headers: { "Content-Type": "application/json" },
        });
        originTableData.value = response.data.data; // 存储原始数据
        console.log(originTableData.value);
        tableData.value = response.data.data; // 初始化显示数据
      } catch (error) {
        console.log(error);
      }
    };

    // 搜索方法
    const handleSearch = () => {
      tableData.value = originTableData.value.filter((item) => {
        const specKeyMatch = searchInfo.specKey
          ? item.specKey.includes(searchInfo.specKey)
          : true;
        const displayNameMatch = searchInfo.displayName
          ? item.displayName.includes(searchInfo.displayName)
          : true;
        const prefixMatch = searchInfo.prefix
          ? item.prefix.includes(searchInfo.prefix)
          : true;
        return specKeyMatch && displayNameMatch && prefixMatch;
      });
    };

    // 重置方法
    const handleReset = async () => {
      // 清空搜索条件
      searchInfo.specKey = "";
      searchInfo.displayName = "";
      searchInfo.prefix = "";
      await getList();
      ElMessage.success("数据已刷新");
    };

    const formRules = {
      specKey: [{ required: true, message: "请输入规格名称", trigger: "blur" }],
      displayName: [
        { required: true, message: "请输入中文名称", trigger: "blur" },
      ],
      prefix: [
        { required: true, message: "请输入规格符号", trigger: "blur" },
        {
          pattern: /^[a-zA-Z0-9]*[a-zA-Z]$/,
          message: "符号只能包含字母和数字，且不能以数字结尾",
        },
      ],
      dataType: [
        { required: true, message: "请输入数据类型", trigger: "blur" },
      ],
    };

    const dialogVisible = ref(false);
    const dialogEditVisible = ref(false);
    const specFormRef = ref<FormInstance>();
    const specForm = reactive<SpecItem>({
      id: 0,
      specKey: "",
      displayName: "",
      prefix: "",
      dataType: "",
    });

    const handleAddSpec = () => {
      dialogVisible.value = true;
    };

    const handleSubmit = () => {
      specFormRef.value?.validate(async (valid) => {
        if (valid) {
          let data = JSON.stringify({
            specKey: specForm.specKey,
            displayName: specForm.displayName,
            prefix: specForm.prefix,
            dataType: specForm.dataType,
          });
          //console.log(data);
          try {
            const response = await request({
              method: "post",
              url: "inventory/specification/createSpecification",
              headers: {
                "Content-Type": "application/json",
              },
              data: data,
            });
            if (response.data.success) {
              dialogVisible.value = false;
              getList(); //刷新数据
            }
          } catch (error) {
            console.log(error);
          }
        }
      });
    };

    const handleDialogClose = () => {
      specFormRef.value?.resetFields();
    };

    // 添加编辑相关独立状态
    const editFormRef = ref<FormInstance>();
    const editForm = reactive<SpecItem>({
      id: 0,
      specKey: "",
      displayName: "",
      prefix: "",
      dataType: "",
    });

    // 编辑方法
    const handleEdit = (row: SpecItem) => {
      //console.log(row);
      // 使用对象解构避免引用问题
      Object.assign(editForm, {
        id: row.id,
        specKey: row.specKey,
        displayName: row.displayName,
        prefix: row.prefix,
        dataType: row.dataType,
      });
      //console.log(editForm);
      dialogEditVisible.value = true;
    };

    //编辑提交方法
    const handleEditSubmit = () => {
      editFormRef.value?.validate(async (valid) => {
        if (valid) {
          try {
            const response = await request({
              method: "post",
              url: "inventory/specification/editSpecification",
              headers: { "Content-Type": "application/json" },
              data: JSON.stringify({
                ...editForm,
              }),
            });
            if (response.data.success) {
              ElMessage.success("规格编辑提交成功");
              console.log(response.data.data);
              dialogEditVisible.value = false;
              getList(); // 刷新数据
            }
          } catch (error) {
            console.error("编辑提交失败:", error);
            ElMessage.error("编辑提交失败");
          }
        }
      });
    };

    // 修改4：添加编辑弹窗关闭处理
    const handleEditDialogClose = () => {
      editFormRef.value?.resetFields();
    };

    // 生命周期钩子
    onMounted(() => {
      getList();
    });

    return {
      searchInfo,
      tableData,
      formRef,
      handleSearch,
      handleReset,
      handleAddSpec,
      handleEdit,
      dialogVisible,
      dialogEditVisible,
      specForm,
      specFormRef,
      formRules,
      handleSubmit,
      handleDialogClose,
      editForm,
      editFormRef,
      handleEditSubmit,
      handleEditDialogClose,
    };
  },
});
</script>


<style scoped>
.layout {
  width: 100%;
  height: 100%;
  background-color: #f5f6f9;
  padding-top: 20px;
}
.main-box {
  width: 98%;
  height: 85vh;
  background-color: #ffffff;
  margin: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.tit {
  height: 40px;
  line-height: 40px;
  font-weight: 600;
  font-size: 20px;
  text-indent: 1em;
}
.selector-box {
  margin: 10px 20px;
}
.flex-container {
  display: flex;
  flex-flow: row wrap;
  column-gap: 12px;
  align-items: flex-end;
}
.input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}
.btn-list {
  border: 1px solid #e1e3e5;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  margin: 0 20px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
}
.table-box {
  height: calc(100% - 60px);
  flex: 1;
  margin: 0 20px;
  border: none;
  overflow: auto;
}
</style>